<template>
  <div class="knowledge" @mouseup="MicrophoneActive = false">
    <div class="updata">
      <el-button style="width: 88px;font-size: 12px;height: 34px;  margin-right: 5px;color: black;"
        @click="toNAS">查看文件</el-button>
      <el-upload v-model:file-list="fileList" style="height: 32px;" multiple :limit="3" :http-request="handleUpload">
        <el-button style="width: 88px;font-size: 12px;" type="primary">上传文件</el-button>
      </el-upload>
    </div>
    <div class="knowledge-grzsk" v-if="dataLiat.length === 0">
      <p>Hi，我是你的<span>AI助手</span>～</p>
      <p>快速精准地查找用户指定或描述的文件，提升查找效率并简化文件管理流程。</p>
      <p><span>· </span>个性化</p>
      <p><span>· </span>知识管理</p>
      <p><span>· </span>内容整合</p>
    </div>
    <div v-else class="knowledge-content">
      <div :class="`content-list ${item.type}`" v-for="item, index in dataLiat">
        <span :class="`${item.type}-item`" :style="item.message.length == 0 ? 'color:transparent' : ''"
          v-loading="item.message.length == 0">
          {{ item.message.length == 0 ? '你好' : '' }}
          {{
            item.message }}</span>
        <div class="item-button" v-if="item.type === 'it' && item.message.length > 0">
          <el-button @click="regenerate(index)" round><span class="icon-Refresh"></span><span
              style="color: black;font-size: 12px;margin-left: 4px;">重新生成</span></el-button>
          <el-button round @click="palySuspend(item.message)"><span
              :class="`${isPalySuspend ? 'icon-play' : 'icon-suspend'}`"></span>
            <div ref="shu" class="shu">
              <span></span>
              <span></span>
              <span></span>
              <span></span>
              <span></span>
              <span></span>
              <span></span>
              <span></span>
              <span></span>
              <span></span>
              <span></span>
              <span></span>
              <span></span>
              <span></span>
              <span></span>
              <span></span>
            </div>
          </el-button>
        </div>
      </div>

    </div>
    <div class="knowledge-search">
      <div class="knowledge-search-input">
        <div class="input-button" style="display: flex;">
          <div v-show="search.length > 0" @click="search = ''" class="icon-clear"></div>
          <div :class="`icon-Microphone ${MicrophoneActive ? 'Microphone-active' : ''}`"
            @mousedown="MicrophoneActive = true"></div>
          <el-button type="primary" @click="querysubmit">
            <span class="icon-aircraft"></span>
          </el-button>
        </div>
        <el-input class="textareaInput" resize="none" type="textarea" v-model="search" style="width: 100%;"
          placeholder="请输入问题，可通过 Shift + 回车换行">
          <!-- <template #suffix> -->
          <!-- </template> -->
        </el-input>
      </div>
    </div>

  </div>
</template>

<script setup>
import { ref, onBeforeUnmount, watch } from 'vue'
import { uploadImg } from "@/api/index.js";
import { query } from "@/api/index"
import { ElMessage } from 'element-plus'
import { useRouter } from "vue-router";
const router = useRouter();
const search = ref('')
const shu = ref(null)
const isPalySuspend = ref(true)
const isSetInterval = ref(0)
const MicrophoneActive = ref(false)
const fileList = ref([])

const str = ref('')

const newStr = ref('')
//内容
const dataLiat = ref([
])
const itOBJ = ref({
  type: "it",
  message: ''
})
const palySuspend = (content) => {
  isPalySuspend.value = !isPalySuspend.value
  if (!isPalySuspend.value) {
    let i = 0
    Array.from(shu.value[0].children).forEach((item) => {
      item.style.height = 4
    })
    isSetInterval.value = setInterval(() => {
      if (i === 13) i = 0
      let arr = [[0, 8], [2, 14], [3, 20], [5, 8]]
      for (let j = 0; j < shu.value[0].children.length; j++) {
        shu.value[0].children[j].style.height = 4 + 'px'
      }

      if (i >= 11) {
        arr.splice(arr.length - 1, 1)
      }
      arr.forEach((ele) => {

        shu.value[0].children[ele[0] + i].style.height = ele[1] + 'px'
      })
      if (i >= 11) {
        shu.value[0].children[shu.value[0].children.length - 1].style.height = 4 + "px"
      }
      i++
    }, 90)
  } else {
    isSetInterval.value && clearInterval(isSetInterval.value)
  }
}
watch(str, (v) => {
  itOBJ.value.message = str.value.split('data:').reduce((str, item) => {
    return item.length > 0 ? str + JSON.parse(item)?.message : str
  }, '')
})
const toNAS = () => {
  router.push("/NASFiles")
}

const handleUpload = (e) => {
  const formData = new FormData();
  const reader = new FileReader();
  reader.readAsArrayBuffer(e.file); // 读取文件为 ArrayBuffer
  reader.onload = async (loadEvent) => {
    const arrayBuffer = loadEvent.target.result;
    // ArrayBuffer 现在包含了文件的二进制数据
    // 接下来可以将其添加到 FormData 中
    formData.append('file', new Blob([arrayBuffer], { type: e.file.type }));
    formData.append("chunkNumber", 1)
    formData.append("chunkSize", e.file.size)
    formData.append("currentChunkSize", 1048)
    formData.append("totalSize", 1048)
    formData.append("identifier", `1048-${e.file.name.split('.')[1]}`)
    formData.append("filename", e.file.name)
    formData.append("relativePath", e.file.name)
    formData.append("totalChunks", 1)
    formData.append("path", '/data/Personal knowledge')
    await uploadImg(formData)
    fileList.value = []
    ElMessage.success("上传成功")
  }
}
//提交问答
const querysubmit = async () => {
  console.log(search.value)
  const message = search.value
  search.value = ""
  if (search.length <= 0) return
  dataLiat.value.push({
    type: "my",
    message
  })
  itOBJ.value = {
    type: "it",
    message: ''
  }
  dataLiat.value.push(itOBJ.value)
  setTimeout(() => {
    document.querySelector('.knowledge-content').scrollTo(0, document.querySelector('.knowledge-content').scrollHeight);
  }, 10)
  try {
    const res = await query(message)
    str.value = res
    // if (code === 200) {
    //   itOBJ.value.message = str
    // }
    setTimeout(() => {
      document.querySelector('.knowledge-content').scrollTo(0, document.querySelector('.knowledge-content').scrollHeight);
    }, 10)

  } catch (error) {
    console.log('网络出错！')
    // itOBJ.value.message = '网络出错！'
  }

}

//重新生成
const regenerate = async (index) => {
  const message = dataLiat.value[index - 1].message
  dataLiat.value[index].message = ""
  try {
    const { data, code } = await query(message)
    if (code === 200) {
      const str = data.reduce((acc, curr, index) => {
        if (data.length - 3 >= index) {
          return acc + curr
        } else {
          return acc
        }
      }, '')
      dataLiat.value.splice(index, 1)
      dataLiat.value.push({
        type: "it",
        message: str
      })
      setTimeout(() => {
        document.querySelector('.knowledge').scrollTo(0, document.querySelector('.knowledge').scrollHeight);
      }, 10)
    }

  } catch (error) {
    dataLiat.value[index].message = '网络出错！'
    console.log('网络出错！')
  }
}
onBeforeUnmount(() => {
  isSetInterval.value && clearInterval(isSetInterval.value)
})
</script>

<style lang="scss" scoped>
.knowledge {
  height: 100%;
  width: 100%;
  position: relative;

  .updata {
    height: 80px;
    display: flex;
    justify-content: end;
    align-items: center;
    margin-right: 67px;
  }

  .knowledge-grzsk {
    width: 70%;
    border-radius: 8px;
    background: #FFF;
    display: flex;
    flex-direction: column;
    padding: 16px;
    inset: 0;
    margin: 0 auto;

    p {
      &:nth-child(1) {
        color: #191919;
        font-size: 17px;
        font-weight: 600;
        margin-bottom: 12px;

        span {
          color: #427BFF;
        }
      }

      &:nth-child(2) {
        color: #191919;
        font-size: 14px;
        margin-bottom: 16px;
      }

      &:nth-child(3),
      &:nth-child(4),
      &:nth-child(5) {
        color: #191919;
        font-size: 14px;
        margin-bottom: 14px;

        span {
          color: #427BFF;
          font-weight: 600;
        }
      }
    }
  }

  .knowledge-content {
    width: 100%;
    height: 80%;
    padding: 60px;
    overflow: hidden;
    overflow-y: auto;

    .content-list {
      width: 100%;
      position: relative;

    }

    .it {
      display: flex;
      justify-content: start;

      .it-item {
        width: auto;
        padding: 12px 16px;
        margin: 10px 0;
        border-radius: 6px;
        background-color: #fff;


      }

      .item-button {
        position: absolute;
        left: 0;
        bottom: -30px;

        .shu {
          display: flex;
          width: 64px;
          height: 100%;
          margin-left: 3px;
          align-items: center;

          span {
            transition: all 0.1s;
            display: flex;
            // width: 2px;
            // height: 4px;
            // border: none;
            margin-right: 2px;
            border-radius: 1px;
            width: 2px;
            height: 4px;
            background-color: #555;

            &:nth-child(7),
            &:nth-child(12) {
              height: 8px;
            }

            &:nth-child(9) {
              height: 14px;
            }

            &:nth-child(10) {
              height: 20px;
            }
          }
        }
      }
    }

    .my {
      display: flex;
      justify-content: end;

      .my-item {
        color: #fff;
        width: auto;
        margin: 10px 0;
        padding: 12px 16px;
        background-color: var(--el-color-primary);
        border-radius: 6px;
      }

    }
  }

  .knowledge-search {
    width: 100%;
    bottom: 40px;
    left: 50%;
    padding: 0 60px;
    transform: translate(-50%, 0);
    position: absolute;

    .knowledge-search-input {
      margin-top: 20px;
      position: relative;

      :deep(.textareaInput) {
        .el-textarea__inner {
          padding-right: 150px !important;
        }

        /* 隐藏默认的滚动条 */
        textarea::-webkit-scrollbar {
          width: 0;
          background: transparent;
          /* 将滚动条背景设置为透明 */
        }

        textarea {
          scrollbar-width: none;
          /* Firefox 隐藏滚动条 */
          -ms-overflow-style: none;
          /* IE 隐藏滚动条 */
        }
      }

      .input-button {
        display: flex;
        justify-content: end;
        align-items: center;
        position: absolute;
        width: 120px;
        right: 20px;
        top: 50%;
        transform: translate(0, -50%);
        z-index: 1;



        .Microphone-active {
          background: url('@/assets/image/Microphone1.svg') no-repeat center;
          background-color: var(--el-color-primary);
        }

        div {
          &:nth-child(1) {
            margin-right: 10px;
          }
        }
      }
    }
  }


}






.icon-Microphone {
  margin-right: 18px;
  margin-left: 10px;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  transition: all 0.5s;
  background: url('@/assets/image/Microphone.svg') no-repeat center;
}

.icon-clear {
  width: 16px;
  height: 16px;
  background: url('@/assets/image/clear.svg') no-repeat center;
}

.icon-aircraft {
  width: 16px;
  height: 16px;
  background: url('@/assets/image/aircraft.svg') no-repeat center;
  background-size: 16px 16px;
}

.icon-Refresh {
  width: 16px;
  height: 16px;
  background: url('@/assets/image/Refresh.svg') no-repeat center;
}

.icon-suspend {
  width: 16px;
  height: 16px;
  background: url('@/assets/image/suspend.svg') no-repeat center;
}

.icon-play {
  width: 16px;
  height: 16px;
  background: url('@/assets/image/play.svg') no-repeat center;
}
</style>
